package com.chenyun.gateway.filter;

import cn.dev33.satoken.same.SaSameUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.Serializable;

/**
 * sa-token配置下的全局过滤器配置
 * @author: Lonni
 * @date: 2022/11/7 0007 11:12
 */
@Component
@Slf4j
public class SaTokenGlobalFilter implements GlobalFilter, Ordered, Serializable {

    private static final long serialVersionUID = -1131036574536618226L;

    public SaTokenGlobalFilter(){
        log.info("SaTokenGlobalFilter--->");
    }

    /**
     * 过滤器 加入idtoken
     * 设置web请求所有的服务的入口都需要经过网关去访问,如果越过网关单独访问了子服务是会阻断的
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        /**
         * 透传idtoken给下游
         */
        ServerHttpRequest request = exchange.getRequest()
                .mutate()
                .header(SaSameUtil.SAME_TOKEN,SaSameUtil.getToken())
                .build();
        final ServerWebExchange newExchange = exchange.mutate().request(request).build();
        return chain.filter(newExchange);
//        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}



